package cn.wetcland.service;

import cn.TCSP;
import cn.hutool.crypto.symmetric.AES;
import cn.wetcland.dao.WetclandPlayerDao;
import cn.wetcland.item.SeniorItems;
import cn.wetcland.pojo.WetclandPlayer;
import org.apache.ibatis.session.SqlSession;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.Date;
import java.util.Map;

public class RegisterService {

    public RegisterService(Player player, String[] args) {
        SqlSession openSession = TCSP.getSqlSessionFactory().openSession(true);
        WetclandPlayerDao mapper1 = openSession.getMapper(WetclandPlayerDao.class);
        WetclandPlayer one = mapper1.findOne(player.getName());
        openSession.close();
        if (one != null) {
            player.sendMessage("§c不好意思，此游戏账号已被注册，请重新更换游戏名登录");
            return;
        }
        Map<String, Object> map = (Map<String, Object>) TCSP.getPlayerAttr().get(player.getName());
        boolean lr = (boolean) map.get("lr");
        if (player == null || lr) {
            player.sendMessage("§a已登录");
            return;
        } else if (!args[0].equals(args[1])) {
            player.sendMessage("§c两次密码不一致, 请重新输入指令");
            return;
        } else {
            SqlSession sqlSession = TCSP.getSqlSessionFactory().openSession(true);
            WetclandPlayerDao mapper = sqlSession.getMapper(WetclandPlayerDao.class);
            // Base64 加密
            AES aes = new AES("taniloveyouandey".getBytes());
            String s = aes.encryptBase64(args[0]);
            // 处理数据
            WetclandPlayer wetclandPlayer = new WetclandPlayer();
            wetclandPlayer.setPlayerName(player.getName());
            wetclandPlayer.setPassword(s);
            wetclandPlayer.setRegDate(new Date());
            wetclandPlayer.setIp(player.getAddress().getAddress().getHostAddress());
            wetclandPlayer.setLevel(1);
            // 给予玩家小助手
            player.getInventory().addItem(SeniorItems.mainMenuItem());
            // 给予新手礼包
            player.getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD),
                    new ItemStack(Material.DIAMOND_HELMET), new ItemStack(Material.DIAMOND_CHESTPLATE),
                    new ItemStack(Material.DIAMOND_BOOTS), new ItemStack(Material.DIAMOND_LEGGINGS),
                    new ItemStack(Material.FIREWORK_ROCKET, 6));
            mapper.addNewPlayer(wetclandPlayer);
            player.kickPlayer("§c[Wetcland]§d注册成功: §a请重新登录哟~");
            sqlSession.close();
        }
    }

}
